import React, { Component } from 'react';
import axios from './../../axios';
import { 
	Card,
	ConfigProvider,
	Pagination,
	Table,
	Modal,
	Form,
	Input,
	Button,
	message,
	Select,
	Tag,
	Transfer
} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import zhCN from 'antd/es/locale/zh_CN';
import Utils from './../../utils/utils';

const Option = Select.Option;

class Notice extends Component {
	state = {
		dataSource: [],//公告列表数据
		count: 0,//公告总条数
		requestParams: {//请求列表数据的参数
			field: "", 
			value: "", 
			page: 1, 
			limit: 10
		},
		pageSizeOptions:["10","20","50"],//表格显示每页多少条分页记录数
		isNoticeCreate: false,//发布公告模态框
		isReadVisible: false,//查看公告详情
	}
	
	formRef = React.createRef();//发布公告表单
	readFormRef = React.createRef();//查看公告详情
	
	//获取列表数据
	requestList = (data) => {
		axios.ajax({
			url: "/Manager/NoticeMng/noticeRetrieve", 
			method: "post",
			data: data,
		}).then(res=>{
			if(res.code === 0){
				//Table的数据没有key就报错，自己加一个key
				let resData = res.result.data.map((item, index)=>{
					let key = index;
					return {...item, key}
				})
				this.setState({
					dataSource: resData,
					count: res.result.count
				})
			}
		}).catch(err=>{
		})
	}
	
	//分页功能，点击某页
	pageChange= (current, pageSize) => {
		let data = {...this.state.requestParams};
		data.page = current;
		data.limit = pageSize;
		this.setState({
			requestParams: data
		})
		this.requestList(data);
	}
	
	//分页功能，选择每页显示几个
	pageSizeChange = (current, pageSize) => {
		let data = {...this.state.requestParams};
		data.page = 1;
		data.limit = pageSize;
		this.setState({
			requestParams: data
		})
		this.requestList(data);
	}
	
	//获取用户信息，发布公告选择的用户
	requestUserList = (data) => {
		axios.ajax({
			url: "/Manager/UserMng/userRetrieve", 
			method: "post",
			data: data,
		}).then(res=>{
			if(res.code === 0){
				//Transfer的数据格式
				let resData = res.result.data.map((item, index)=>{
					let key = item.id;
					let title = item.user_name;
					return {"title":title, "key":key.toString()}
				})
				this.setState({
					mockData: resData
				})
			}
		}).catch(err=>{
		})
	}
	
	//点击发布公告
	noticeCreate = () => {
		this.setState({isNoticeCreate: true});
	}
	
	//发布公告提交
	noticeSubmit = values => {
		let data = {
			"type": 1,
			"title":　values.title,
			"content": values.content,
			"receiver": {
				"type": values.receiverType,
				"userids": this.state.targetKeys
			}
		}
		axios.ajax({
			headers: { "Content-Type": "application/json"},
			url: "/Manager/NoticeMng/noticeCreate",
			method: "post",
			data: data
		}).then(res=>{
			if(res.code === 0){
				message.success("消息发送成功");
				this.requestList(this.state.requestParams);
			}
		})
		this.setState({
			isNoticeCreate: false
		})
		this.formRef.current.resetFields();
	}
	
	//点击查看公告
	noticeUpdate = (record) => {
		this.setState({
			isReadVisible: true,
			selectedItem: record,
		});
		setTimeout(()=>{
			//为模态框赋值
			if(record.receiver.type === "SOME"){
				this.readFormRef.current.setFieldsValue({
					"title":record.title,
					"content":record.content,
					"receiverType":record.receiver.type,
					"user":record.user.user_name
				});
				this.setState({
					targetKeys: record.receiver.userids
				})
			}else{
				this.readFormRef.current.setFieldsValue({
					"title":record.title,
					"content":record.content,
					"receiverType":record.receiver.type,
					"user":record.user.user_name,
				});
			}
		},500)
	}
	
	//删除公告
	noticeDelete = (record) => {
		Modal.confirm({
			title: `确认删除 ？`,
			icon: <ExclamationCircleOutlined />,
			content: "想好后再操作喔",
			okText: "确认删除",
			cancelText: "取消",
			onOk:()=>{
				axios.ajax({
					url: "/Manager/NoticeMng/noticeDelete",
					method: "post",
					data: {id: record._id}
				}).then(res=>{
					if(res.code === 0){
						message.success(res.msg);
						this.requestList({
							field: "", 
							value: "", 
							page: 1, 
							limit: 5
						});
					}
				})
			}
		})
	}
	
	//选择用户穿梭框满足筛选条件时返回true
	filterOption = (inputValue, option) => {
		return option.title.indexOf(inputValue) > -1;
	}
	
	//穿梭框变化时
	handleUserChange = (targetKeys) => {
		this.setState({targetKeys})
	}
	
	componentDidMount(){
		//获取用户列表
		this.requestUserList({
			field: "",
			value: "",
			page: "",
			limit: ""
		});
		//获取公告列表信息
		this.requestList(this.state.requestParams);
	}
	
	render(){
		const layout = {
		    labelCol: { span: 4 },
		    wrapperCol: { span: 20 },
		};
		const tailLayout = {
		    wrapperCol: { offset: 4, span: 20 },
		};
		const columns = [
			{
				title: "标题",
				dataIndex: "title"
			},{
				title: "接收群体",
				dataIndex: "receiver",
				render: type => {
					if(type && type.type){
						return type.type === "ALL" ? <Tag color="blue">全部用户</Tag>
						:<Tag color="cyan">部分用户</Tag>;
					}else{
						return "本条数据不规范"
					}
				}
			},{
				title: "发布者",
				dataIndex: "user",
				render: user => {
					if(user){
						return user.user_name
					}else{
						return "本条数据不规范"
					}
				}
			},{
				title: "创建时间",
				dataIndex: "create_time",
				render: Utils.formateDate
			},{
				title: '操作',
				key: 'action',
				fixed: 'right',
				width: 180,
				render: (text, record) => {
					return <div>
						<Tag color="#108ee9" onClick={() => this.noticeUpdate(record)}>查看详情</Tag>
						<Tag color="#f45656" onClick={() => this.noticeDelete(record)}>删除</Tag>
					</div>
				}
			}
		];
		const count = this.state.count;
		const current = this.state.requestParams.page;
		const pageSize = this.state.requestParams.limit;
		return (
			<div style={{padding: 20}}>
				<Card className="page-search-wrap">
					<Button type="primary" onClick={this.noticeCreate}>发布公告</Button>
				</Card>
				<Card>
					<Table
						columns={columns}
						dataSource={this.state.dataSource}
						pagination={false}
					/>
					<ConfigProvider locale={zhCN}>
						<Pagination
							showQuickJumper
							showSizeChanger
							current={current}
							defaultPageSize={pageSize}
							total={count}
							showTotal={total => `共 ${total} 条`}
							pageSizeOptions={this.state.pageSizeOptions}
							onChange={this.pageChange}
							onShowSizeChange={this.pageSizeChange}
						/>
					</ConfigProvider>
				</Card>
				<Modal
					title="发布公告"
					visible={this.state.isNoticeCreate}
					onCancel={()=>this.setState({isNoticeCreate: false})}
					footer={null}
					width={600}
				>
					<Form
						{...layout}
						ref={this.formRef}
						onFinish={this.noticeSubmit}
					>
						<Form.Item
							label="公告标题"
							name="title"
							rules={[
								{required: true, message: "请输入标题"},
								{max:50, message: "标题过长"},
							]}
						>
						    <Input autoComplete="off" />
						</Form.Item>
						<Form.Item
							label="公告内容"
							name="content"
							rules={[
								{required: true, message: "请输入内容"},
							]}
						>
						    <Input.TextArea rows={5}  autoComplete="off" />
						</Form.Item>
						<Form.Item
							name="receiverType" 
							label="接收群体" 
							rules={[{ required: true, message: "请选择" }]}
						>
							<Select
							    allowClear
							>
							    <Option value="ALL">全部用户</Option>
							    <Option value="SOME">部分用户</Option>
							</Select>
						</Form.Item>
						<Form.Item
							noStyle
							shouldUpdate={(prevValues, currentValues) => prevValues.receiverType !== currentValues.receiverType}
						>
							{({ getFieldValue }) => {
								return getFieldValue('receiverType') === 'SOME' ? (
									<Form.Item
										label="接收用户"
										name="userids"
									>
										<Transfer
											listStyle={{width: 200,height: 400}}
											titles={["待选用户","已选用户"]}
											showSearch
											searchPlaceholder="输入用户名"
											dataSource={this.state.mockData}
											filterOption={this.filterOption}
											targetKeys={this.state.targetKeys}
											onChange={this.handleUserChange}
											render={item=>item.title}
										/>
									</Form.Item>
								) : null;
							}}
						</Form.Item>
						<Form.Item  {...tailLayout}>
							<Button type="primary" htmlType="submit">
							    发送
							</Button>
							<Button htmlType="button" onClick={()=>this.formRef.current.resetFields()}>
								重置
							</Button>
						</Form.Item>
					</Form>
				</Modal>
				<Modal
					title="查看公告详情"
					visible={this.state.isReadVisible}
					onCancel={()=>this.setState({isReadVisible: false})}
					footer={null}
					width={600}
				>
					<Form
						{...layout}
						ref={this.readFormRef}
					>
						<Form.Item
							label="公告标题"
							name="title"
						>
						    <Input disabled />
						</Form.Item>
						<Form.Item
							label="公告内容"
							name="content"
						>
						    <Input.TextArea disabled />
						</Form.Item>
						<Form.Item
							label="发布者"
							name="user"
						>
						    <Input disabled />
						</Form.Item>
						<Form.Item
							name="receiverType" 
							label="接收群体" 
						>
							<Select
							    allowClear
								disabled
							>
							    <Option value="ALL">全部用户</Option>
							    <Option value="SOME">部分用户</Option>
							</Select>
						</Form.Item>
						<Form.Item
							noStyle
							shouldUpdate={(prevValues, currentValues) => prevValues.receiverType !== currentValues.receiverType}
						>
							{({ getFieldValue }) => {
								return getFieldValue('receiverType') === 'SOME' ? (
									<Form.Item
										label="接收用户"
									>
										
									    <Transfer
									    	listStyle={{width: 200,height: 400}}
									    	titles={["待选用户","已选用户"]}
									    	dataSource={this.state.mockData}
									    	targetKeys={this.state.targetKeys}
									    	render={item=>item.title}
											disabled={true}
									    />
									</Form.Item>
								) : null;
							}}
						</Form.Item>
						<Form.Item  {...tailLayout}>
							<Button htmlType="button" onClick={()=>this.setState({isReadVisible:false})}>
								关闭
							</Button>
						</Form.Item>
					</Form>
				</Modal>
			</div>
		)
	}
}

export default Notice;